<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>生成div</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        div{
            width: 40px;
            height: 40px;
            background-color: red;
            position: absolute;
        }
    </style>
</head>
<body>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
    <script>
        $(document).click(function(e){
            let div = $('<div/>')
            div.css({
                left:e.pageX+'px',
                top:e.pageY+'px'
            })
            //Math.round(Math.random()) 表示返回 0或1
            let timer = setInterval(() => {
                //获取 top值 和 left值
                let top = div.offset().top
                let left = div.offset().left
                //如果div出去了，就删除
                if(top<0){
                    div.remove()   //删除div
                    clearInterval(timer)   //清除定时器
                }
                div.css({
                    top:(top-20)+'px',
                    left:Math.round(Math.random())===0?(left-20)+'px':(left+20)+'px'
                })
            }, 200);

            $('body').append(div)
        })
    </script>
</body>
</html>